package com.dak.robot.Service.Impl;

import com.dak.robot.Dao.GroupMessageDao;
import com.dak.robot.Dao.ImageDao;
import com.dak.robot.Entity.GroupMessage;
import com.dak.robot.Service.GroupMessageService;
import net.mamoe.mirai.contact.Contact;
import net.mamoe.mirai.event.events.GroupMessageEvent;
import net.mamoe.mirai.message.data.Image;
import net.mamoe.mirai.message.data.MessageChain;
import net.mamoe.mirai.message.data.MessageChainBuilder;
import net.mamoe.mirai.utils.ExternalResource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URL;
import java.util.List;


@Service
public class GroupMessageServiceImpl implements GroupMessageService {
    @Resource
    private GroupMessageDao groupMessageDao;

    @Resource
    private ImageDao imageDao;

    @Override
    public void insertGroupMessage(GroupMessageEvent groupMessageEvent) {
//        groupMessageEvent.getMessage().get(Image.Key);

        /**
         * 插入消息整体到数据库groupmessage表中
         */
        GroupMessage groupMessage = new GroupMessage();
        groupMessage.setGroupId(groupMessageEvent.getGroup().getId());
        groupMessage.setSenderId(groupMessageEvent.getSender().getId());
        groupMessage.setData(MessageChain.serializeToJsonString(groupMessageEvent.getMessage()));
        groupMessageDao.insertSelective(groupMessage);
        /**
         * 插入图片到数据库image表中
         */
        groupMessageEvent.getMessage().stream().filter(Image.class::isInstance).forEach(item->{
            String str = Image.queryUrl(Image.fromId(((Image) item).getImageId()));
            com.dak.robot.Entity.Image image = new com.dak.robot.Entity.Image();
            try {
                URL url = new URL(str);
                image.setImageId(((Image) item).getImageId());
                image.setData(url.openStream().readAllBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
            imageDao.insert(image);
        });
    }

    @Override
    public MessageChain getGroupMessage(Long sender_id,Long group_id) {
        MessageChainBuilder messageChainBuilder  = new MessageChainBuilder();
        List<GroupMessage> groupmessagelist = groupMessageDao.select(sender_id,group_id);
        groupmessagelist.forEach(item->{
            /**
             * 从数据库groupmessage表中读取数据，存储到List<GroupMessage>列表中
             * 获取消息编号--id和消息时间--savetime，添加到消息链中
             */
            messageChainBuilder.append("消息编号："+item.getId().toString()+"      "+"消息时间:"+item.getSavetime()+'\n');
            /**
             * 逐条记录解析
             */
            MessageChain.deserializeFromJsonString(item.getData()).forEach(temp->{
                /**
                 * 每条记录反序列化后
                 * 逐元素解析
                 * 因为需要按顺序来构建MessageChain
                 * 所以无法使用List.stream().filter(Image.class.IsInstance).forEach(item->{do;})的方法进行遍历
                 */
                if (temp.getClass().isInstance(Image.class))
                {
                    Contact contact = null;
                    String imageId = ((Image)temp).getImageId();
                    com.dak.robot.Entity.Image image;
                    image = imageDao.selectByImageId(imageId);
                    if (image != null){
                        messageChainBuilder.append(contact.uploadImage(ExternalResource.create(image.getData())));
                    }
                    else {
                        messageChainBuilder.append("-----图片已被删除！------");
                    }
                }
                else {
                    messageChainBuilder.append(temp);
                }
            });
            messageChainBuilder.append('\n');
        });
        return messageChainBuilder.build();
    }

    @Override
    public void delectGroupMessage(Long id) {
        /**
         * 通过消息编号(id)获取需要删除的消息
         * 存储到GroupMessage中
         * 判断是否包含图片
         * 如果包含图片，则按照图片Id(imageId)删除image中指定的图片
         * 图片删除部分处理完成后，删除groupmessage中的消息
         */
        MessageChain.deserializeFromJsonString(groupMessageDao.selectById(id).getData()).stream().filter(Image.class::isInstance).forEach(item->{
            imageDao.deleteByImageId(((Image) item).getImageId());
        });
        groupMessageDao.deleteByGroupMessageId(id);
    }

    @Override
    public void deleteGroupMessage(Long sender_id, Long group_id) {
        List<GroupMessage> groupmessagelist = groupMessageDao.select(sender_id,group_id);
        /**
         * 获取需要删除的groupmessage
         */
        groupmessagelist.forEach(item->{
            /**
             * 逐条将需要删除的groupmessage的data反序列化，
             * 找出其中包含图片的部分
             * 按照图片Id(imageId)从image表中删除指定的图片
             * 图片全部删除完毕后，最后再删除groupmessage中的记录
             */
            MessageChain.deserializeFromJsonString(item.getData()).stream().filter(Image.class::isInstance).forEach(temp->{
                imageDao.deleteByImageId(((Image) temp).getImageId());
            });
        });
        groupMessageDao.deleteBySenderIdOrGroupId(sender_id,group_id);
    }


}
